# coding: utf-8
from django.http import HttpResponse
from django.shortcuts import render_to_response
from indexer.psh.models import Hesla, Varianta, Ekvivalence
import simplejson as json
from invenio.config import CFG_SITE_URL
import random
from invenio.search_engine import perform_request_search, print_record
from invenio.dbquery import run_sql

def suggest(request, psh=""):
	if request.REQUEST.__contains__("input"):
		psh = request.REQUEST["input"]
	response = HttpResponse()
	response['Content-Type'] = 'application/javascript'
	hesla = Hesla.objects.filter(heslo__istartswith=psh)
	alt = Varianta.objects.filter(varianta__istartswith=psh, jazyk="cs")
	seznam = [heslo.heslo for heslo in hesla]				
	for heslo in alt:
		seznam.append(heslo.varianta)
	content = json.dumps(seznam)
	if request.GET.get("callback"):
		callback = request.GET.get("callback")
		response.content = "".join([callback, "(", content, ")"])
		return response
	else:
		response.content = content
		return response
#	return HttpResponse(json.dumps(seznam), mimetype='application/json')

def index_text(request):
	response = HttpResponse()
	response['Content-Type'] = 'application/javascript'
	if request.GET.get("text"):
		text = request.GET.get("text")
		directory = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(8))
		directory = "".join(["/tmp/indexer-", directory])
		save_text(text, directory)
		hesla = index(directory)
		hesla = ["".join(["'", heslo.strip("\n|\r|\r\n"), "'"]) for heslo in hesla]
		if len(hesla) > 0:
			content = "".join([u"{", ",".join(hesla), "}"])
		else:
			content = "''"
		if request.GET.get("callback"):
			callback = request.GET.get("callback")
			response.content = "".join([callback, "(", content, ")"])
			return response
		else:
			response.content = content
			return response
	else:
		response.content = "{'Error': 'No text input'}"
		return response

def translate(request, psh=""):
	if "input" in request.REQUEST:
		psh = request.REQUEST["input"]
	try:
		return HttpResponse(json.dumps({
			"pref" : Varianta.objects.get(varianta=psh).id_heslo.heslo,
			"npref" : psh,
		}))
	except:
		try:
			Hesla.objects.get(heslo=psh)
			return HttpResponse(json.dumps({
				"pref" : psh,	
			}))
		except:
			return HttpResponse(json.dumps(False))
	   	
def search(request, psh):
	psh = psh.encode("utf-8")
	# return HttpResponse(psh.__class__.__name__)
	reclist = perform_request_search(p='"%s"' % psh, f="PSH")
	recLen = len(reclist)
	random.shuffle(reclist)
	reclist = reclist[:10]
	titles = ""
	for rec in reclist:
		titles += "<a href='%s' class='documentResult' target='_blank'>%s</a><br />" % ("%s/record/%d" % (CFG_SITE_URL, rec), print_record(rec, format='xt'))
		
	ret = {"recLen" : recLen, "titles" : titles}
	return HttpResponse(json.dumps(ret), mimetype='application/json')
	
	
def suggest_conference(req):
	ret = {"count" : 0, "names" : []}
	if req.REQUEST.__contains__("conference"):
		reslist = []
		
		for res in run_sql("SELECT value FROM bib71x WHERE tag='7112_a' AND value LIKE '%%%s%%'" % req.REQUEST["conference"]):
			reslist.append(res[0])
		ret["count"] = len(reslist)
		reslist.sort(key=lambda x: x.lower())
		ret["names"] = reslist[:50]
	return HttpResponse(json.dumps(ret), mimetype="application/json")
		
def keyword2psh(req, psh):
	return HttpResponse(mapKeyword2psh(psh))
	
def mapKeyword2psh(psh):
	res = ""
	psh = psh.lower()
	try:
		res = Hesla.objects.get(heslo=psh).heslo
		return res
	except:
		pass
	try:
		res = Ekvivalence.objects.get(ekvivalent=psh).id_heslo.heslo
		return res
	except:
		pass
	try:
		res = Varianta.objects.get(varianta=psh).id_heslo.heslo
		return res
	except:
		pass
	return res
	
	
def main(request):
	return render_to_response("index.html", {})
